package jwt_250328;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class jwtDemo1 {

    // 密钥（在实际应用中应该安全存储，不要硬编码）
    private static final String SECRET_KEY = "your-256-bit-secret-key-1234567890ab"; // 至少32字节用于HS256
    private static final long EXPIRATION_TIME = 86400000; // 过期时间，单位毫秒（这里设为1天）

    // 生成JWT
    public static String generateJwt(String username, Map<String, Object> claims) {
        // 当前时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 创建密钥
        Key signingKey = new SecretKeySpec(SECRET_KEY.getBytes(), SignatureAlgorithm.HS256.getJcaName());

        // 构建JWT
        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)           // 自定义声明
                .setSubject(username)        // 设置用户名
                .setIssuedAt(now)            // 设置签发时间
                .setExpiration(new Date(nowMillis + EXPIRATION_TIME)) // 设置过期时间
                .signWith(signingKey, SignatureAlgorithm.HS256);      // 使用HS256算法签名

        return builder.compact();
    }
    // 解析JWT
    public static Claims parseJwt(String jwt) {
        try {
            // 创建密钥
            Key signingKey = new SecretKeySpec(SECRET_KEY.getBytes(), SignatureAlgorithm.HS256.getJcaName());

            // 解析JWT
            return Jwts.parserBuilder()
                    .setSigningKey(signingKey)
                    .build()
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            // 处理异常，例如签名无效、令牌过期等
            System.out.println("JWT解析失败: " + e.getMessage());
            return null;
        }
    }
    // 测试代码
    public static void main(String[] args) {
        // 示例：生成JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put("user_name", "wusong");
        claims.put("scope", new String[]{"read", "write"});
        claims.put("aud",new String[]{"hsmain"});

        String jwt = generateJwt("wusong", claims);
        System.out.println("生成的JWT: " + jwt);

        // 示例：解析JWT
        Claims parsedClaims = parseJwt(jwt);
        if (parsedClaims != null) {
            System.out.println("解析结果:");
            System.out.println("用户名: " + parsedClaims.getSubject());
            System.out.println("user_name: " + parsedClaims.get("user_name"));
            System.out.println("scope: " + parsedClaims.get("scope"));
            System.out.println("签发时间: " + parsedClaims.getIssuedAt());
            System.out.println("过期时间: " + parsedClaims.getExpiration());
            Object o = parsedClaims.get("aud");
            System.out.println(o.getClass().getName());
        }
    }
}
